<template>
  <div>
    <div>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <i class="el-icon-lx-cascades"></i>
            饮食信息
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="container">
        <div class="handle-box">
          <el-input v-model="query.username" placeholder="用户姓名" class="handle-input mr10"></el-input>
          <el-select v-model="query.category" placeholder="就餐状态" class="handle-select mr10">
            <el-option v-for="item in options" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-button type="primary" @click="handleSearch"><el-icon style="margin-right: 5px">
              <Search />
            </el-icon>搜索</el-button>
          <el-button type="primary" @click="resetSearch">清空</el-button>
          <el-button type="primary" @click="handleExportData"><el-icon style="margin-right: 5px">
              <Download />
            </el-icon>导出饮食信息</el-button>
        </div>
        <el-table :data="tableData" border class="table" ref="mydietTable" header-cell-class-name="table-header"
          v-loading="loading">
          <el-table-column type="expand" width="1">
            <template #default>
                <el-table :data="childDetailData" v-loading="loadingDetail">
                  <el-table-column label="序号" width="70" align="center">
                    <template #default="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column label="食物名称" prop="foodName" />
                  <el-table-column label="蛋白质(g)" prop="protein" />
                  <el-table-column label="脂肪(g)" prop="fat" />
                  <el-table-column label="碳水(g)" prop="carbohydrate" />
                  <el-table-column label="热量(千卡)" prop="caloric" />
                  <el-table-column label="食物重量(g)" prop="dietRecordDetail.foodWeight" />
                </el-table>
            </template>
          </el-table-column>
          <el-table-column label="序号" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="user.username" label="用户姓名" width="150" align="center">
          </el-table-column>
          <el-table-column prop="user.realname" label="真实姓名" width="150" align="center">
          </el-table-column>
          <el-table-column prop="dietRecordName" label="食谱名称" align="center">
          </el-table-column>
          <el-table-column label="就餐类别" width="120" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.category == '0'
                  ? 'success'
                  : scope.row.category == '1'
                    ? 'success'
                    : scope.row.category == '2'
                      ? 'success'
                      : scope.row.category == '3'
                        ? 'warning'
                        : 'warning'
                ">
                {{
                  scope.row.category == '0'
                  ? '早餐'
                  : scope.row.category == '1'
                    ? '午餐'
                    : scope.row.category == '2'
                      ? '晚餐'
                      : scope.row.category == '3'
                        ? '加餐'
                        : '无'
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="就餐形式" width="120" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.form == '0'
                  ? 'success'
                  : scope.row.form == '1'
                    ? 'success'
                    : 'warning'
                ">
                {{
                  scope.row.form == '0'
                  ? '在家'
                  : scope.row.form == '1'
                    ? '外出'
                    : '无'
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" align="center" width="200"></el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="text" icon="el-icon-edit" @click="handleShowDetail(scope.row)"><el-icon
                  style="margin-right: 5px">
                  <Edit />
                </el-icon>详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
            :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, reactive, onMounted, onBeforeMount } from 'vue'
import { ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { ElMessage } from 'element-plus'
import XLSX from 'xlsx'
import router from '../../router'
export default {
  setup() {
    const mydietTable = ref()
    const loading = ref(true)
    const loadingDetail = ref(true)
    // const useRouter = useRouter()
    const tableData = ref([])
    const childDetailData = ref([])
    const pageTotal = ref(0)
    const form = reactive({
      content: '',
    })

    const options = [
      {
        value: '0',
        label: '早餐',
      },
      {
        value: '1',
        label: '午餐',
      },
      {
        value: '2',
        label: '晚餐',
      },
      {
        value: '3',
        label: '加餐',
      },
    ]

    const query = reactive({
      dietRecordName: '',
      username: '',
      category: '',
      form: '',
      pageIndex: 1,
      pageSize: 5,
    })
    const ruleFormRef = ref()
    const ruleForm = ref({})

    // 查询操作
    const handleSearch = () => {
      getData()
    }

    // 重置
    const resetSearch = () => {
      query.username = ''
      query.category = ''
      getData()
    }
    // 分页导航
    const handlePageChange = (val) => {
      loading.value = true
      query.pageIndex = val
      getData()
    }

    //展开显示详情
    const handleShowDetail = async (row) => {
      tableData.value.map((item) => {
        if (row.dietRecordId != item.dietRecordId) {
          mydietTable.value.toggleRowExpansion(item, false)
        }
      })
      const res = await getDetail(row.dietRecordId)
      if(res.data.data.foods.length>0){
        childDetailData.value = res.data.data.foods
        mydietTable.value.toggleRowExpansion(row)
        loadingDetail.value = false
      }
    }
    // 获取饮食详情数据
    const getDetail = (dietRecordId) => {
      return request
        .request({
          url: '/dietRecord/getDietRecordById',
          params: {
            dietRecordId,
          },
          method: 'get',
        })
        .then((res) => {
          return res
        })
        .catch((e) => {
          console.log(e)
        })
    }
    // 获取表格数据
    const getData = () => {
      request
        .request({
          url: '/dietRecord/getDietRecordsByPageAndCondition',
          params: {
            username: query.username,
            dietRecordName: query.dietRecordName,
            category: query.category,
            form: query.form,
            currentPage: query.pageIndex,
            pageSize: query.pageSize,
          },
          method: 'get',
        })
        .then((res) => {
          tableData.value = res.data.data.rows
          pageTotal.value = res.data.data.count
          loading.value = false
        })
        .catch((e) => {
          console.log(e)
        })
    }

    getData()

    /*
    * @description:
    * @param {Object} json 服务端发过来的数据
    * @param {String} name 导出Excel文件名字
   
    * @param {String} titleArr 导出Excel表头
   
    * @param {String} sheetName 导出sheetName名字
    * @return:
    */
    const exportData = ref([])
    const titleArr = [
      '创建时间',
      '更新时间',
      '食物名称',
      '就餐形式',
      '就餐状态(0早餐 1午餐 2晚餐 3加餐)',
      '用户ID',
      '真实姓名',
      '用户名',
    ] //表头中文名
    // 获取导出表格数据
    const handleExportData = () => {
      request
        .request({
          url: '/dietRecord/getDietRecordsByPageAndCondition',
          params: {
            currentPage: 1,
            pageSize: pageTotal.value,
          },
          method: 'get',
        })
        .then((res) => {
          //获取当前页的数据
          exportData.value = res.data.data.rows
          exportExcel(exportData.value, '饮食情况', titleArr, 'sheetName')
        })
        .catch((e) => {
          console.log(e)
        })
        .finally()
    }
    // 导出函数
    const exportExcel = (json, name, titleArr, sheetName) => {
      /* convert state to workbook */
      var data = new Array()
      var keyArray = new Array()
      const getLength = function (obj) {
        var count = 0
        for (var i in obj) {
          if (obj.hasOwnProperty.call(i)) {
            count++
          }
        }
        return count
      }

      for (const key1 in json) {
        if (Object.prototype.hasOwnProperty.call(json, key1)) {
          const element = json[key1]
          var rowDataArray = new Array()
          for (const key2 in element) {
            if (key2 == 'dietRecordId') {
              continue
            }
            if (Object.hasOwnProperty.call(element, key2)) {
              var element2 = ''
              var element3 = ''
              if (key2 == 'user') {
                element2 = element[key2].username
                element3 = element[key2].realname
                rowDataArray.push(element3)
              } else if (key2 == 'category') {
                if (element[key2] == 0) {
                  element2 = '早餐'
                } else if (element[key2] == 1) {
                  element2 = '午餐'
                } else if (element[key2] == 2) {
                  element2 = '晚餐'
                } else if (element[key2] == 3) {
                  element2 = '加餐'
                }
              } else if (key2 == 'form') {
                if (element[key2] == 0) {
                  element2 = '在家'
                } else if (element[key2] == 1) {
                  element2 = '外出'
                }
              } else {
                element2 = element[key2]
              }
              rowDataArray.push(element2)
              if (keyArray.length < getLength(element)) {
                keyArray.push(key2)
              }
            }
          }
          data.push(rowDataArray)
        }
      }
      // keyArray为英文字段表头
      data.splice(0, 0, keyArray, titleArr)
      const ws = XLSX.utils.aoa_to_sheet(data)
      const wb = XLSX.utils.book_new()
      // 此处隐藏英文字段表头
      var wsrows = [{ hidden: true }]
      ws['!rows'] = wsrows // ws - worksheet
      XLSX.utils.book_append_sheet(wb, ws, sheetName)
      /* generate file and send to client */
      XLSX.writeFile(wb, name + '.xlsx')
    }

    return {
      mydietTable,
      loading,
      loadingDetail,
      query,
      pageTotal,
      tableData,
      form,
      ruleForm,
      ruleFormRef,
      options,
      getData,
      handleSearch,
      handleShowDetail,
      childDetailData,
      handlePageChange,
      resetSearch,
      exportExcel,
      handleExportData,
      exportData,
      titleArr,
    }
  },
}
</script>
<style lang="scss" scoped>
:deep(.el-table__expand-icon) {
  visibility:hidden !important;
	}
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 150px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.content {
  color: rgb(32, 27, 27);
  font-size: 35rpx;
  text-overflow: ellipsis;
  z-index: -1;
  display: -webkit-box;
  word-break: break-all;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  overflow: hidden;
}

.containertwo {
  display: flex;
  align-items: center;
}
</style>

<style>
.el-upload--text {
  height: auto;
  width: auto;
}

.mavonEditor {
  width: 100%;
  height: 100%;
}
</style>
